import { useState, useEffect } from 'react'
import classnames from 'classnames'
import { getChannels, addChannel, deleteChannel, selectTab } from '@/store/actions'
import { useDispatch, useSelector } from 'react-redux'
import Icon from '@/components/Icon'
import styles from './index.module.scss'

const Channels = ({ onClose }) => {
  const dispatch = useDispatch()
  // channelActiveIndex   reducer里的状态，切换数据的下标
  const { channels, restChannels, channelActiveIndex } = useSelector(state => state.home)
  const [isEdit, setIsEdit] = useState(false)
  useEffect(() => {
    dispatch(getChannels())
  }, [dispatch])
  const onChangeEdit = () => {
    setIsEdit(!isEdit)
  }
  const onAddChannel = item => {
    // console.log('点击了');
    dispatch(addChannel(item))
  }
  // 频道点击事件
  const onMyChannelClick = (item, index) => {
    // 判断是否为编辑状态
    if (isEdit) {
      // 删除
      dispatch(deleteChannel(item))
    } else {
      // 切换
      dispatch(selectTab(index))
      onClose()
    }
  }

  return (
    <div className={styles.root}>
      <div className="channel-header">
        <Icon type="iconbtn_channel_close" onClick={onClose} />
      </div>
      <div className="channel-content">
        <div className={classnames('channel-item', isEdit ? 'edit' : '')}>
          <div className="channel-item-header">
            <span className="channel-item-title">我的频道</span>
            <span className="channel-item-title-extra">点击进入频道</span>
            <span className="channel-item-edit" onClick={onChangeEdit}>
              {isEdit ? '保存' : '编辑'}
            </span>
          </div>
          <div className="channel-list">
            {channels.map((item, index) => {
              return (
                // 将点击的数据传给onMyChannelClick方法
                <span
                  key={item.id}
                  onClick={() => onMyChannelClick(item, index)}
                  className={classnames(
                    'channel-list-item',
                    index === channelActiveIndex ? 'selected' : ''
                  )}
                >
                  {item.name}
                  <Icon type="iconbtn_tag_close" />
                </span>
              )
            })}
          </div>
        </div>

        <div className="channel-item">
          <div className="channel-item-header">
            <span className="channel-item-title">频道推荐</span>
            <span className="channel-item-title-extra">点击添加频道</span>
          </div>
          <div className="channel-list">
            {restChannels.map(item => (
              <span key={item.id} className="channel-list-item" onClick={() => onAddChannel(item)}>
                + {item.name}
              </span>
            ))}
          </div>
        </div>
      </div>
    </div>
  )
}

export default Channels
